終於第十天了呀,我覺得要撐滿30天好難,奇怪了我為甚麼要這麼勉強自己,壓力爆棚壓
題號:75 標題:Sort Colors 難度:Medium
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
我的程式碼
void sortColors(int* nums, int numsSize){
int i,f=0,s=0,t=0,temp=0;
for(i=0;i<numsSize;i++){
if(nums[i]==0){
f++;
}else if(nums[i]==1){
s++;
}else{
t++;
}
}
for(i=0;i<numsSize;i++){
if(f!=0){
nums[i] = 0;
f--;
}else if(s!=0){
nums[i] = 1;
s--;
}else if(t!=0){
nums[i] = 2;
t--;
}
}
return 0;
}
DAY10心得
這題一開始想用sort解決,但後來發現,要寫sort還不如用無腦解,反正數字只有三種,先跑一輪計算各有幾個,在把正確的數量依大小填回原本的陣列就解完了,最大的心得就是,不要小看無腦解,能達成目標的都是好解。